package com.example.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.domain.Category;
import com.example.domain.Dish;
import com.example.domain.DishFlavor;
import com.example.dto.DishDto;
import com.example.result.JsonResult;
import com.example.untils.RedisContent;
import com.example.service.CategoryService;
import com.example.service.DishFlavorSerivce;
import com.example.service.DishService;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController extends BaseController{    //菜品表
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorSerivce dishFlavorSerivce;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //新增菜品
    @PostMapping
    public JsonResult save(@RequestBody DishDto dishDto){
        log.info("图片:"+dishDto.getImage());
        dishService.saveWithFlavor(dishDto);
        //删除缓存
        String DishKey=RedisContent.SELECTID_DISH_KEY+dishDto.getCategoryId();
        stringRedisTemplate.delete(DishKey);
        return new JsonResult(1,"新增成功");
    }
    //菜品信息分页查询
    @GetMapping("/page")
    public JsonResult page(Integer page,Integer pageSize,String name){
        IPage<DishDto> dtoIPage=new Page<>(page,pageSize);

        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Dish::getName,name);
        queryWrapper.orderByAsc(Dish::getUpdateTime);

        dishService.getDishDtoPage(dtoIPage,queryWrapper);


        return new JsonResult(1,"",dtoIPage);
    }
    //根据id查询菜品信息和对应的口味信息
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable Long id){
        Dish dish = dishService.getById(id);
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorSerivce.list(queryWrapper);
        //合并菜品和菜品口味
        DishDto dishDto=new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(list);
        return new JsonResult(1,"",dishDto);
    }
    //修改菜品
    @PutMapping
    public JsonResult update(@RequestBody DishDto dishDto){
        log.info("图片:"+dishDto.getImage());
        //先更新数据库
        dishService.updateWithFlavor(dishDto);

        //删除缓存
        String DishKey=RedisContent.SELECTID_DISH_KEY+dishDto.getCategoryId();
        stringRedisTemplate.delete(DishKey);
        return new JsonResult(1,"新增成功");
    }
    //套餐添加页提供菜品列表，前台首页获取列表信息
    @GetMapping("/list")
    public JsonResult list(Dish dish){
        List<DishDto> dishDtoList=null;
        //查看redis中的菜品
        String DishKey=RedisContent.SELECTID_DISH_KEY+dish.getCategoryId();
        List<String> Sblist=stringRedisTemplate.opsForList().range(DishKey,0,-1);
        for (String s : Sblist) {
            DishDto dishDto=JSONUtil.toBean(s, DishDto.class);
            dishDtoList.add(dishDto);
        }
        if(dishDtoList!=null){
            return new JsonResult(1,"",dishDtoList);
        }
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorSerivce.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        System.out.println("菜品数据:"+dishDtoList);
        //存储到redis
        for (DishDto dishDto : dishDtoList) {
            String s = JSONUtil.toJsonStr(dishDto);
            stringRedisTemplate.opsForList().leftPush(DishKey,s);
        }
        stringRedisTemplate.expire(DishKey,RedisContent.SELECTID_DISH_TTL,TimeUnit.MINUTES);

        return new JsonResult(1,"",dishDtoList);
    }
}
